<template>
  <div class="user-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button
            v-has-role="'admin'"
            type="primary"
            @click="handleAdd"
          >
            <el-icon><Plus /></el-icon>
            新增用户
          </el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <mobile-search
        :search-form="searchForm"
        @search="handleSearch"
        @reset="handleReset"
      >
        <template #default="{ searchForm }">
          <el-form-item label="用户名">
            <el-input
              v-model="searchForm.username"
              placeholder="请输入用户名"
              clearable
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
            >
              <el-option label="启用" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-form-item>
        </template>
      </mobile-search>

      <!-- 表格区域 - 使用移动端优化组件 -->
      <mobile-table
        :data="tableData"
        :current-page="pagination.page"
        :page-size="pagination.size"
        :total="pagination.total"
        :get-row-key="(row) => row.id"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
        <!-- 桌面端表格 -->
        <template #desktop-table>
          <el-table
            v-loading="loading"
            :data="tableData"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="nickname" label="昵称" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column prop="role" label="角色">
              <template #default="{ row }">
                <el-tag :type="row.role === 'admin' ? 'danger' : 'primary'">
                  {{ row.role === 'admin' ? '管理员' : '普通用户' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
              <template #default="{ row }">
                <el-switch
                  v-has-permission="'system:user:status'"
                  v-model="row.status"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleStatusChange(row)"
                />
                <el-tag v-if="!hasPermission('system:user:status')" :type="row.status ? 'success' : 'danger'">
                  {{ row.status ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column label="操作" width="200">
              <template #default="{ row }">
                <el-button
                  v-has-role="'admin'"
                  type="primary"
                  size="small"
                  @click="handleEdit(row)"
                >
                  编辑
                </el-button>
                <el-button
                  v-has-role="'admin'"
                  type="danger"
                  size="small"
                  @click="handleDelete(row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>

        <!-- 移动端卡片 -->
        <template #mobile-card="{ row }">
          <div class="user-card">
            <div class="user-header">
              <div class="user-info">
                <h3>{{ row.nickname }}</h3>
                <p class="username">@{{ row.username }}</p>
              </div>
              <div class="user-status">
                <el-tag :type="row.role === 'admin' ? 'danger' : 'primary'" size="small">
                  {{ row.role === 'admin' ? '管理员' : '普通用户' }}
                </el-tag>
                <el-tag :type="row.status ? 'success' : 'danger'" size="small">
                  {{ row.status ? '启用' : '禁用' }}
                </el-tag>
              </div>
            </div>

            <div class="user-details">
              <div class="detail-item">
                <span class="label">邮箱：</span>
                <span class="value">{{ row.email }}</span>
              </div>
              <div class="detail-item">
                <span class="label">创建时间：</span>
                <span class="value">{{ row.createTime }}</span>
              </div>
            </div>

            <div class="user-actions">
              <el-button
                v-has-role="'admin'"
                type="primary"
                size="small"
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button
                v-has-role="'admin'"
                type="danger"
                size="small"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
              <el-switch
                v-has-permission="'system:user:status'"
                v-model="row.status"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(row)"
                style="margin-left: 8px;"
              />
            </div>
          </div>
        </template>
      </mobile-table>


    </el-card>

    <!-- 用户表单对话框 -->
    <mobile-form
      v-model="dialogVisible"
      :title="dialogTitle"
      :loading="submitLoading"
      @confirm="handleSubmit"
      @close="handleDialogClose"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="!userForm.id" label="密码" prop="password">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
      </el-form>
    </mobile-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { usePermission } from '@/utils/permissionMiddleware'
import MobileTable from '@/components/MobileTable/index.vue'
import MobileForm from '@/components/MobileForm/index.vue'
import MobileSearch from '@/components/MobileSearch/index.vue'

const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)
const userFormRef = ref()

const { hasPermission } = usePermission()

const searchForm = reactive({
  username: '',
  status: ''
})

const userForm = reactive({
  id: null,
  username: '',
  nickname: '',
  email: '',
  role: 'user',
  password: ''
})

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const tableData = ref([])
const selectedRows = ref([])

const dialogTitle = computed(() => {
  return userForm.id ? '编辑用户' : '新增用户'
})

const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 模拟数据
const mockData = [
  {
    id: 1,
    username: 'admin',
    nickname: '管理员',
    email: 'admin@example.com',
    role: 'admin',
    status: 1,
    createTime: '2023-01-01 10:00:00'
  },
  {
    id: 2,
    username: 'user1',
    nickname: '用户1',
    email: 'user1@example.com',
    role: 'user',
    status: 1,
    createTime: '2023-01-02 10:00:00'
  },
  {
    id: 3,
    username: 'user2',
    nickname: '用户2',
    email: 'user2@example.com',
    role: 'user',
    status: 0,
    createTime: '2023-01-03 10:00:00'
  }
]

const fetchData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    tableData.value = mockData
    pagination.total = mockData.length
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  fetchData()
}

const handleReset = () => {
  searchForm.username = ''
  searchForm.status = ''
  handleSearch()
}

const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  Object.assign(userForm, row)
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟删除操作
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    console.log('取消删除')
  }
}

const handleStatusChange = async (row) => {
  try {
    // 模拟状态切换
    ElMessage.success(`用户状态已${row.status ? '启用' : '禁用'}`)
  } catch (error) {
    ElMessage.error('状态切换失败')
    row.status = row.status ? 0 : 1 // 回滚状态
  }
}

const handleSubmit = async () => {
  if (!userFormRef.value) return
  
  try {
    const valid = await userFormRef.value.validate()
    if (!valid) return
    
    submitLoading.value = true
    
    // 模拟提交
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success(userForm.id ? '更新成功' : '创建成功')
    dialogVisible.value = false
    fetchData()
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  resetForm()
}

const resetForm = () => {
  userForm.id = null
  userForm.username = ''
  userForm.nickname = ''
  userForm.email = ''
  userForm.role = 'user'
  userForm.password = ''
  if (userFormRef.value) {
    userFormRef.value.clearValidate()
  }
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleSizeChange = (size) => {
  pagination.size = size
  fetchData()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  fetchData()
}

onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
.user-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}



.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 移动端卡片样式 */
.user-card {
  .user-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;

    .user-info {
      flex: 1;

      h3 {
        margin: 0 0 4px 0;
        font-size: 16px;
        font-weight: 600;
        color: #333;
      }

      .username {
        margin: 0;
        font-size: 14px;
        color: #666;
      }
    }

    .user-status {
      display: flex;
      flex-direction: column;
      gap: 4px;
      align-items: flex-end;
    }
  }

  .user-details {
    margin-bottom: 12px;

    .detail-item {
      display: flex;
      margin-bottom: 6px;
      font-size: 14px;

      &:last-child {
        margin-bottom: 0;
      }

      .label {
        color: #666;
        min-width: 80px;
      }

      .value {
        color: #333;
        flex: 1;
        word-break: break-all;
      }
    }
  }

  .user-actions {
    display: flex;
    align-items: center;
    gap: 8px;
    padding-top: 12px;
    border-top: 1px solid #f0f0f0;
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .user-container {
    padding: 10px;
  }

  .search-area {
    :deep(.el-form--inline .el-form-item) {
      display: block;
      margin-right: 0;
      margin-bottom: 10px;
    }
  }

  .card-header {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;

    .el-button {
      width: 100%;
    }
  }
}
</style>
